import cv2
import os
import glob


class Tools:
    def __init__(self):
        self.dir_pic = "D://git_example/datasets/coco128/images/train2017"
        self.dir_txt = "D://git_example/datasets/coco128/labels/train2017"
        self.names = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat',
                      'traffic light',
                      'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep',
                      'cow',
                      'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase',
                      'frisbee',
                      'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard',
                      'surfboard',
                      'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana',
                      'apple',
                      'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
                      'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard',
                      'cell phone',
                      'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
                      'teddy bear',
                      'hair drier', 'toothbrush']
    
    def rect(self, file):
        pic = f"{self.dir_pic}/{file}.jpg"
        img = cv2.imread(pic)
        imgInfo = img.shape
        height = imgInfo[0]
        width = imgInfo[1]
        print (1111,height,width)
        ax = self.txt2coordinate(file, width, height)
        print(ax)
        for x in ax:
            x1 = (int(x['cx'] - x['w'] / 2), int(x['cy'] - x['h'] / 2))
            x4 = (int(x['cx'] + x['w'] / 2), int(x['cy'] + x['h'] / 2))
            print(x1, x4)
            cv2.rectangle(img, x1, x4, (0, 0, 255), 2)
            cv2.putText(img, x['cat'], (int(x['cx']), int(x['cy'])), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255, 255, 255), 2)
        cv2.imshow("image", img)
        k = cv2.waitKey(4000)
    
    def txt2coordinate(self, file, w, h):
        txt = f"{self.dir_txt}/{file}.txt"
        res = []
        with open(txt, "rb") as f:
            t = f.read().decode().split("\n")
            for i in t:
                if i == "": continue
                ii = i.split(" ")
                res.append({
                    "cat": self.names[int(ii[0])],
                    "cx": float(ii[1]) * w,
                    "cy": float(ii[2]) * h,
                    "w": float(ii[3]) * w,
                    "h": float(ii[4]) * h,
                })
            return res


if __name__ == '__main__':
    file = "000000000030"
    t = Tools()
    t.rect(file)
